
from argparse import ArgumentParser
from sys import exit

from .searchcc import find_cxx_compiler, find_cc_compiler
from .execcc import exec_script

from .utils import check_exists
from .log import verbose, error, set_mute_level


def main():
    arg_parser = ArgumentParser('runcc', description='run cc file as a script!')

    arg_parser.add_argument('script', help='script filepath')
    arg_parser.add_argument('-v', type=int, default=9, help='verbose mute level, default = 9')
    arg_parser.add_argument('-f', '--force', action='store_true', default=False, help='force compile')

    args, ext_args = arg_parser.parse_known_args()

    script: str = args.script

    set_mute_level(args.v)

    if ext_args:
        verbose('runcc: extra args: ' + ' '.join(ext_args))

    if not check_exists(script):
        error('runcc: no such file: ' + script)
        return 1
    
    if (script.endswith('.c')):
        compiler = find_cc_compiler()
    else:
        compiler = find_cxx_compiler()

    if not compiler:
        error('runcc: no compiler found, make sure g++ can be execute through command line or ' + 
              'setup CXX_COMPILER/C_COMPILER path to your g++/gcc in your environment variables')
        return 1
    verbose('runcc: Compiler found: ' + compiler)

    return exec_script(compiler, script, ext_args, args)


if __name__ == '__main__':
    exit(main())
